package com.anli1.tool;

import cn.hutool.json.JSONObject;
import lombok.Data;
import org.apache.ibatis.mapping.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Configuration
@Data
public class TokenEncryption {
    @Value("${token.encryption.key}")
    private String key;

    @Value("${token.encryption.iv}")
    private String iv;

    @Value("${token.encryption.algorithm}")
    private String algorithm;


    private SecretKeySpec AES;

    private  IvParameterSpec ivSpec;
    private  Cipher cipher;

    public String getKey() {
        return key;
    }

    public String getIv() {
        return iv;
    }

    public String getAlgorithm() {
        return algorithm;
    }

   public String getTokenEncryption(String data) throws Exception {
        //用于包装密钥 --包装向量
       extracted();
       //指定加密
        //加密
        cipher.init(Cipher.ENCRYPT_MODE, AES, ivSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes());
       String encryptedBase64 = Base64.getEncoder().encodeToString(encrypted);


       return encryptedBase64;

    }

    private void extracted() throws Exception {
        if(AES==null)
        {
            byte[] rawKey = adjustKeyLength(key, 16); // 16字节=128位
            AES=new SecretKeySpec(rawKey,algorithm);
        }
        if(ivSpec==null)
        {
            byte[] ivBytes = adjustKeyLength(iv, 16);
            ivSpec = new IvParameterSpec(ivBytes);
        }
        if(cipher == null)
        {
             cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }
    }

 private    SecretKeySpec secretKey;

    public String retToken(String data) throws Exception {
        if(secretKey==null)
        {
            byte[]  rawKey = adjustKeyLength(key, 16); // 16字节=128位
            secretKey = new SecretKeySpec(rawKey, algorithm);
        }

        if(ivSpec==null)
        {
            byte[] ivBytes = adjustKeyLength(iv, 16);
            ivSpec = new IvParameterSpec(ivBytes);
        }
        // 指定解密算法和模式
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // 初始化解密器
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

        // 解密Base64编码的加密数据
        byte[] decodedEncryptedData = Base64.getDecoder().decode(data);
        byte[] decryptedData = cipher.doFinal(decodedEncryptedData);

        // 返回解密后的原始字符串
        return new String(decryptedData, "UTF-8");


    }

    private byte[] adjustKeyLength(String key, int length) throws Exception {
        byte[] keyBytes = key.getBytes("UTF-8");
        if (keyBytes.length == length) {
            return keyBytes;
        } else if (keyBytes.length < length) {
            // 如果长度不足，使用0填充
            byte[] paddedKey = new byte[length];
            System.arraycopy(keyBytes, 0, paddedKey, 0, keyBytes.length);
            return paddedKey;
        } else {
            // 如果长度超出，截取前面的部分
            byte[] shortenedKey = new byte[length];
            System.arraycopy(keyBytes, 0, shortenedKey, 0, length);
            return shortenedKey;
        }
    }


}
